from typing import Dict, Optional
from datetime import datetime
from tortoise.expressions import Q

from app.models.detection import Detection
from app.schemas.detection import DetectionCreate, DetectionUpdate
from app.core.crud import CRUDBase


class DetectionController(CRUDBase[Detection, DetectionCreate, DetectionUpdate]):
    def __init__(self):
        super().__init__(model=Detection)

    async def create(self, *, obj_in: DetectionCreate, operator_id: int) -> Detection:
        """创建检测记录"""
        obj_dict = obj_in.model_dump()
        obj_dict["operator_id"] = operator_id
        db_obj = await self.model.create(**obj_dict)
        return db_obj

    async def get_detection_list(
        self,
        *,
        page: int = 1,
        page_size: int = 10,
        detection_type: Optional[int] = None,
        operator_id: Optional[int] = None,
        start_time: Optional[str] = None,
        end_time: Optional[str] = None,
    ) -> Dict:
        """获取检测记录列表"""
        q = Q()
        if detection_type is not None:
            q &= Q(detection_type=detection_type)
        if operator_id is not None:
            q &= Q(operator_id=operator_id)
        if start_time:
            q &= Q(detection_time__gte=datetime.fromisoformat(start_time))
        if end_time:
            q &= Q(detection_time__lte=datetime.fromisoformat(end_time))

        total = await self.model.filter(q).count()
        items = await self.model.filter(q).order_by("-detection_time").offset(
            (page - 1) * page_size
        ).limit(page_size).all()

        return {
            "total": total,
            "items": [await item.to_dict() for item in items],
        }


detection_controller = DetectionController() 